import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';

import { LoveRecycManageService } from '../love-recyc-manage.service';
import { BehaviorSubject, Observable, of } from 'rxjs';
import { catchError, debounceTime, map, switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-love-hot-search',
  templateUrl: './love-hot-search.component.html',
  styleUrls: ['./love-hot-search.component.scss']
})
export class LoveHotSearchComponent implements OnInit, OnDestroy {

  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0,
    pages: 0
  };
  tableData: any = [1, 2];

  // 新增编辑Modal
  isVisible: boolean = false;
  subModalLoding: boolean = false;
  modalType: number = 0;
  modalItem: any = {};
  validateForm!: FormGroup;

  nzFilterOption = () => true;
  getModelEvalOptions: any = [];

  // 机型options<请求防抖>
  searchChange$ = new BehaviorSubject('');
  isInputLoading: boolean = false;

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private services: LoveRecycManageService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      modelId: [null, [Validators.required]]
    });

    /**
     * 机型选择防抖
     * ----------------------------------------------------------------
     */
    this.searchChange$
      .asObservable()
      .pipe(debounceTime(500))
      .subscribe((value: any) => {
        if (!value) {
          this.getModelEvalOptions = [];
          return
        }
        this.getModelEvalList(value);
      })

    this.loadTable();
  }

  ngOnDestroy(): void {
    this.searchChange$.unsubscribe();
  }

  /**
   * 查询机型下拉
   * @param searchVal 搜索值
   * @param isShow 
   * @returns 
   */
  async getModelEvalList(searchVal: any) {
    let params = {
      name: searchVal,
      page: 1,
      pageSize: 999999
    }
    // const res: any = await this.services.getHotmodelEvalList(params);
    this.isInputLoading = true;
    const res: any = await this.services.getRecycleModelList(params);
    this.isInputLoading = false;
    if (res.code == 0) {
      const { records } = res.data || {};
      this.getModelEvalOptions = records || [];
    } else {
      this.getModelEvalOptions = [];
      this.message.error(res.message);
    }
  }

  searchModel(value: any) {
    this.searchChange$.next(value);
  }

  async loadTable() {
    const res: any = await this.services.gethotSearchList({});
    if (res.code == 0) {
      this.tableData = res.data || [];
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * 排序
   * @param num 1：上移，2：下移
   * @param id 
   */
  async sortTable(num: number, id: any) {
    let res: any = null;
    if (num == 1) {
      res = await this.services.hotSearchSortUp(id);
    } else {
      res = await this.services.hotSearchSortDown(id);
    }
    
    if (res.code == 0) {
      this.message.success('操作成功');
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  // 删除
  async deleteItem(item: any) {
    let params = {
      id: item.id,
      status: 0
    }
    const res: any = await this.services.updateHotSearchItem(params);
    if (res.code == 0) {
      this.message.success('删除成功');
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * 新增编辑
   * @param item
   * @param num 0：新增，1：编辑 
   */
  async showModal(num: number, item?: any) {
    this.validateForm.reset();
    this.modalType = num;

    if (item) {
      await this.getModelEvalList(item.modelName);
      this.validateForm.get('modelId')?.setValue(item.modelId);
      this.modalItem = item;
    }
    
    this.isVisible = true;
  }
  handleCancel() {
    this.isVisible = false;
  }
  async submitForm() {
    if (this.validateForm.valid) {
      let params = {
        ...this.validateForm.value
      }
      let res: any = null;
      switch (this.modalType) {
        case 0:
          // add
          res = await this.services.saveHotSearchItem(params);
          break;
        case 1:
          // edit
          params.id = this.modalItem.id;
          res = await this.services.updateHotSearchItem(params);
          break;
      }

      if (res.code == 0) {
        this.message.success('操作成功');
        this.loadTable();
        this.isVisible = false;
      } else {
        this.message.error(res.message);
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // 页数改变时的回调函数
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  disabledMoveBtn(index?: number): boolean {
    if (this.tableParams.page == this.tableParams.pages && index == this.tableData.length - 1) {
      return true
    } else {
      return false
    }
  }
}
